#include <head.h>


int main() {
    int pipefd[2];
    pid_t pid;

    // 创建无名管道
    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    // 创建子进程
    pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (pid == 0) {
        // 子进程
        close(pipefd[0]);  // 关闭读端

        // 向管道写入数据
        char *message = "Hello, Parent!";
        write(pipefd[1], message, strlen(message) + 1);

        close(pipefd[1]);  // 关闭写端

        exit(EXIT_SUCCESS);
    } else {
        // 父进程
        close(pipefd[1]);  // 关闭写端

        // 从管道读取数据
        char buffer[1024];
        ssize_t bytesRead = read(pipefd[0], buffer, sizeof(buffer));
        if (bytesRead == -1) {
            perror("read");
            exit(EXIT_FAILURE);
        }

        printf("Parent received: %s\n", buffer);

        close(pipefd[0]);  // 关闭读端

        exit(EXIT_SUCCESS);
    }
}
